<template>
  <!-- app版本管理 -->
  <div class="p-2">
    <!-- 顶部搜索 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="操作系统" prop="os">
              <el-select v-model="queryParams.os" placeholder="请选择" clearable style="width: 100px">
                <el-option label="安卓" value="android" />
                <el-option label="IOS" value="ios" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="enable">
              <el-select v-model="queryParams.enable" placeholder="请选择" clearable style="width: 90px">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" icon="Search">搜索</el-button>
              <el-button @click="resetQuery" icon="Refresh">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="hover">
      <!-- 功能按钮 -->
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" plain @click="handleAdd()"
              v-hasPermi="['sys:appVersion:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain :disabled="single" icon="Edit" @click="handleUpdate()"
              v-hasPermi="['sys:appVersion:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain :disabled="single" icon="Delete" @click="handleDelete()"
              v-hasPermi="['sys:appVersion:remove']">删除</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <!-- 列表 -->
      <el-table ref="verTableRef" v-loading="loading" :data="verList" max-height="550"
        @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="操作系统" prop="os" :show-overflow-tooltip="true" align="center" width="">
          <template #default="scope">{{ osFilters(scope.row.os) }}</template>
        </el-table-column>
        <el-table-column label="版本" prop="version" :show-overflow-tooltip="true" align="center" width="" />
        <el-table-column label="版本号" prop="versionCode" :show-overflow-tooltip="true" align="center" width="" />
        <el-table-column label="强制升级" prop="force" :show-overflow-tooltip="true" align="center" width="">
          <template #default="scope">{{ forceFilters(scope.row.force) }}</template>
        </el-table-column>
        <el-table-column label="升级日志" prop="upgradeLog" :show-overflow-tooltip="true" align="center" width="200" />
        <el-table-column label="渠道" prop="channel" :show-overflow-tooltip="true" align="center" width="" />
        <el-table-column label="状态" prop="enable" align="center" width="">
          <template #default="scope">
            <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="添加时间" prop="createTime" align="center" :show-overflow-tooltip="true"
          width="140">
          <template #default="scope">{{ scope.row.createTime.slice(0, -3) }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="180">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['sys:appVersion:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['sys:appVersion:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="verFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="操作系统" prop="os">
          <el-select v-model="form.os" clearable placeholder="请选择操作系统" style="width: 100%">
            <el-option label="安卓" value="android" />
            <el-option label="IOS" value="ios" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input v-model="form.version" clearable placeholder="请输入版本" />
        </el-form-item>
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model.number="form.versionCode" clearable placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="强制升级" prop="force">
          <el-radio-group v-model="form.force">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="升级日志" prop="upgradeLog">
          <el-input v-model="form.upgradeLog" :rows="2" type="textarea" clearable placeholder="请输入升级日志" />
        </el-form-item>
        <el-form-item label="渠道" prop="channel">
          <el-input v-model="form.channel" clearable placeholder="请输入渠道" />
        </el-form-item>
        <el-form-item label="地址" prop="url">
          <el-input v-model="form.url" clearable placeholder="请输入地址" />
          <el-upload v-if="form.os === 'android'" action="#" :http-request="beforeRemoveUrl" :show-file-list="false">
            <el-button v-loading="loadingUrl" type="primary" style="margin-top: 10px">点击上传</el-button>
          </el-upload>
          <!-- <el-upload v-if="form.os === 'android'" :action="huonseom.url" :headers="huonseom.headers"
            :on-success="beforeRemoveUrl" :show-file-list="false">
            <el-button v-loading="loadingUrl" type="primary" style="margin-top: 10px">点击上传</el-button>
          </el-upload> -->
        </el-form-item>
        <el-form-item label="是否启用" prop="enable">
          <el-radio-group v-model="form.enable">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Version">
import upload from "@/utils/upload";
import { listVersion, addVersion, updateVersion, delVersion, enableVersion } from '@/api/system/version/index';
import { VerVO, VerForm, VerQuery } from '@/api/system/version/types';
// 获取toke的方法
import { globalHeaders } from "@/utils/request";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const huonseom = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/file/upload'
})

// const verList = ref<Array<VerVO>>([]);
const verList = ref<VerVO[]>([]);
const loading = ref(true)
const showSearch = ref(true)
const ids = ref<Array<string | number>>([])
const infos = ref<VerVO[]>([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const loadingUrl = ref(false)

const queryFormRef = ref<ElFormInstance>();
const verFormRef = ref<ElFormInstance>();

/**
 * 校验规则
 * @param rule 
 * @param value 
 * @param callback 
 */
const isNum = (rule: any, value: any, callback: any) => {
  const price = /^[0-9]*$/
  if (!price.test(value)) {
    callback(new Error('版本号只能为数字'))
  } else {
    callback()
  }
}

const initForm: VerForm = {
  os: '',
  version: '',
  versionCode: undefined,
  force: undefined,
  upgradeLog: '',
  channel: '',
  url: '',
  enable: undefined,
}

const data = reactive<PageData<VerForm, VerQuery>>({
  form: { ...initForm },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    os: '',
    enable: undefined,
  },
  rules: {
    os: [{ required: true, message: "请选择操作系统", trigger: "change" }],
    version: [{ required: true, message: "请输入版本", trigger: "blur" }],
    versionCode: [
      { required: true, message: "请输入版本号", trigger: "blur" },
      { validator: isNum, trigger: 'blur' }
    ],
    force: [{ required: true, message: "请选择是否强制升级", trigger: "change" }],
    upgradeLog: [{ required: true, message: "请输入升级日志", trigger: "blur" },],
    url: [{ required: true, message: "请输入地址", trigger: "change" }],
  }
})
const { form, queryParams, rules } = toRefs(data)

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

/**
 * 查询app版本列表列表
 */
const getList = async () => {
  loading.value = true
  const res = await listVersion(queryParams.value);
  verList.value = res.data.list;
  total.value = res.data.total;
  loading.value = false;
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/**
 * 重置搜索
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/**
 * 过滤(操作系统)
 * @param val 
 */
const osFilters = (val: string) => {
  if (val === 'android') {
    return '安卓'
  } else if (val === 'ios') {
    return 'IOS'
  }
}

/**
 * 过滤(强制升级)
 * @param val 
 */
const forceFilters = (val: number) => {
  if (val === 1) {
    return '是'
  } else if (val === 0) {
    return '否'
  }
}

/**
 * 多选框选中数据
 */
const handleSelectionChange = (selection: VerVO[]) => {
  ids.value = selection.map((item: VerVO) => item.id);
  infos.value = selection.map((item: VerVO) => item);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/**
 * 添加app版本
 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加app版本";
}

/**
 * 修改app版本
 */
const handleUpdate = (row?: VerVO) => {
  reset();
  if (row) {
    Object.assign(form.value, row);
  } else {
    Object.assign(form.value, infos.value[0]);
  }
  dialog.visible = true;
  dialog.title = "修改app版本";
}

/**
 * 删除app版本
 */
const handleDelete = async (row?: VerVO) => {
  try {
    const ver = row || infos.value[0];
    if (ver.enable == 1) {
      proxy?.$modal.msgError('请先执行禁用操作');
      return
    }
    await proxy?.$modal.confirm('是否确认删除app版本');
    await delVersion(ver.id);
    getList();
    proxy?.$modal.msgSuccess('删除成功');
  } catch (error) { }
}

/**
 * 启用禁用
 */
const handleStatusChange = async (row: VerVO) => {
  try {
    let text = row.enable === 1 ? "启用" : "停用";
    await enableVersion(row.id);
    proxy?.$modal.msgSuccess(text + "成功");
  } catch (error) {
    row.enable = row.enable === 1 ? 0 : 1;
  }
}

/**
 * 重置新增表单
 */
const reset = () => {
  form.value = { ...initForm };
  verFormRef.value?.resetFields();
}

const beforeRemoveUrl = async (op: any) => {
  loadingUrl.value = true;
  const res = await upload(op.file);
  form.value.url = res;
  // 如果上传成功
  // if (res.code === 200) {
  //   form.value.url = res.data.url;
  // } else {
  //   proxy?.$modal.loading(res.msg);
  // }
  loadingUrl.value = false;
}

/**`
 * 提交按钮
 */
const submitForm = async () => {
  try {
    await verFormRef.value?.validate()
    form.value.id ? await updateVersion(form.value) : await addVersion(form.value);
    proxy?.$modal.msgSuccess(`${form.value.id ? '修改' : '添加'}成功`)
    dialog.visible = false
    getList()
  } catch (error) {
    // proxy?.$modal.msgError("操作失败")
  }
}

/**
 * 取消按钮
 */
const cancel = () => {
  reset()
  dialog.visible = false;
}

onMounted(() => {
  getList();
});
</script>

<style scoped></style>